const routerFuc = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab'];
const whiteList = ['/pages/login/index']


function plusReady() {
  // 关闭程序启动界面
  plus.navigator.closeSplashscreen();
}
// 查询是否关闭启动界面
function hasSplash() {
  if (plus.navigator.hasSplashscreen()) {
    return false;
  } else {
    return true;
  }
}

function onLoad() {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('loginInfo');
    console.log('token', token);
    if (!token) {
      uni.reLaunch({
        url: '/pages/login/index'
      })
      // plusReady();
      resolve(false);
      uni.$on('plusReady', async function(data) {
        await new Promise(resolve => setTimeout(resolve, 300));
        plusReady();
      })
    } else {
      plusReady();
      resolve(true)
    }
  })
}

function addInterceptor(item) {
  uni.addInterceptor(item, {
    invoke(args) {
      const token = uni.getStorageSync('token');
      const currentUrl = args.url;
      const isWhite = whiteList.includes(currentUrl)
      if (!token) {
        if (!isWhite) {
          return uni.redirectTo({
            url: '/pages/login/index'
          })
        }
      } else {
        console.log('token', token);
        return true
      }

      // return false;
    },
    success(args) {
      console.log('拦截成功，拦截事件：', args);
    },
    fail(err) {
      console.log('interceptor-fail', err)
    }
  })
}

/**
 * @function permissionInit  登录拦截
 * 
 */
export async function permissionInit() {
  const isLoad = await onLoad()
  console.log('isLoad', isLoad);
  if (!isLoad) {
    return false;
  }
  for (var i = 0; i < routerFuc.length; i++) {
    addInterceptor(routerFuc[i])
  }
}